package com.zoe.vhr.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.zoe.vhr.model.Hr;
import com.zoe.vhr.service.RedisService;
import com.zoe.vhr.util.R;
import com.zoe.vhr.util.VerifyCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/26
 * @Description 登录接口
 */
@RestController
public class LoginController {
    @Autowired
    RedisService redisService;

    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 用户未登录会重定向到这个地方
     *
     * @return
     */
    @GetMapping("/login")
    public R login() {
        return R.unauthorized("请先登录  login接口");
    }

    /**
     * 获取当前登录的用户
     *
     * @return
     */
    @GetMapping("/currentUser")
    public R currentUser() {
        logger.info("获取当前用户====>{}", DateUtil.today());
        Hr hr = (Hr) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        hr.setPassword(null);
        return R.success(hr);
    }

    /**
     * 生成验证码
     *
     * @return
     */
    @GetMapping("/captchaImage")
    public R captchaImage() {
        HashMap<String, Object> resMap = MapUtil.newHashMap();

        VerifyCodeUtil verifyCodeUtil = VerifyCodeUtil.genVerifyCode();

        String uuid = UUID.fastUUID().toString();
        redisService.setCacheObject(uuid, verifyCodeUtil.getVerifyCode(), 60L, TimeUnit.SECONDS);

        resMap.put("uuid", uuid);
        resMap.put("img", verifyCodeUtil.getVerifyCodeBase64());
        return R.success(resMap);
    }

}
